#include <stdint.h>
#include "interrupt.h"
#include "uart.h"
#include "timer.h"

// Machine Status Register (mstatus)
static inline uint64_t read_mstatus(void) {
    uint64_t val;
    asm volatile("csrr %0, mstatus" : "=r"(val));
    return val;
}

// 读取中断号
static inline uint64_t read_mtval(void) {
    uint64_t val;
    asm volatile("csrr %0, mtval" : "=r"(val));
    return val;
}

static inline uint64_t read_mcause(void) {
    uint64_t val;
    asm volatile("csrr %0, mcause" : "=r"(val));
    return val;
}

// Machine Interrupt Enable Register (mie)
static inline uint64_t read_mie(void) {
    uint64_t val;
    asm volatile("csrr %0, mie" : "=r"(val));
    return val;
}

static inline void write_mstatus(uint64_t val) {
    asm volatile("csrw mstatus, %0" : : "r"(val));
}

static inline void write_mie(uint64_t val) {
    asm volatile("csrw mie, %0" : : "r"(val));
}

void interrupt_init(void) {
    // Clear all interrupt enables
    write_mie(0);
    
    // Enable interrupts globally
    interrupt_enable();
}

void interrupt_enable(void) {
    uint64_t mstatus = read_mstatus();
    mstatus |= MSTATUS_MIE;
    write_mstatus(mstatus);
}

void interrupt_disable(void) {
    uint64_t mstatus = read_mstatus();
    mstatus &= ~MSTATUS_MIE;
    write_mstatus(mstatus);
}


void handle_interrupt(void) {
    uint64_t mcause;
    asm volatile("csrr %0, mcause" : "=r"(mcause));
    
    // 检查是否是中断 (最高位为1)
    if (mcause & 0x8000000000000000ULL) {
        uint64_t cause = mcause & 0x7FFFFFFFFFFFFFFF;
        
        switch (cause) {
            case IRQ_M_TIMER:
                // 调用定时器处理函数
                timer_handler();
                break;
                
            default:
                uart_puts("Unknown interrupt: ");
                // 这里应该添加一个函数打印数字
                uart_puts("\n");
                break;
        }
    } else {
        // 处理异常
        uart_puts("Exception occurred: ");
        // 这里应该添加一个函数打印数字
        uart_puts("\n");
    }
}
